package com.guojiganzhe.subject.application.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 *
 * @author:
 * @date: 2023/12/3
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();//获取当前线程的请求上下文并提取HttpServletRequest对象；
        if (Objects.nonNull(request)) {
            String loginId = request.getHeader("loginId");//从原始请求中获取名为loginId的请求头；
            if (StringUtils.isNotBlank(loginId)) {//如果loginId存在且非空，则将其添加到Feign请求模板中，传递给下游服务。
                requestTemplate.header("loginId", loginId);
            }
        }
    }

}
